package jt.classic.app.info;

import jt.classic.system.ISystem;
import jt.classic.system.SSOAction;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.user.IUser;
import jt.classic.system.user.UserManager;

import net.sf.json.JSONArray;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import org.limp.basework.SimpleBean;
import org.limp.basework.impl.CommonBean4HSQ;
import org.limp.basework.tools.BaseworkUtil;

import org.limp.mine.Controller;
import org.limp.mine.DateTrimmer;
import org.limp.mine.Label;
import org.limp.mine.QueryJack;
import org.limp.mine.QueryJackFactory;
import org.limp.mine.StringTool;

import java.sql.Connection;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 新闻评论控制器
 * @author mido
 *
 */
public class InfoReplyAction extends SSOAction {
    /**
     * 保存评论
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward savereply(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        IUser user = ISystem.getSessionUser(request);

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        String ifid = StringTool.checkString(req.getResource().get("ifid"));

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            InfoManager manager = new InfoManager(conn);

            AInfo info = manager.getAInfoById(ifid);

            if (info.ireceipt()) {
                BaseworkUtil util = new BaseworkUtil();
                SimpleBean sb = BaseworkUtil.analyzerSimpleBean("APP_INFO_RECEIPT",
                        req);
                sb.getResource().put("rtime", DateTrimmer.getYMDHMS());
                sb.getResource().put("rip", request.getRemoteAddr());
                sb.getResource().put("rstatus", "0");

                if (user.id().equals(UserManager.GUEST_USER_ID)) {
                    sb.getResource().put("userid", UserManager.GUEST_USER_ID);
                    sb.getResource()
                      .put("gid",
                        (user.igroup() != null) ? user.igroup().id() : "-1");
                    sb.getResource()
                      .put("gname",
                        (user.igroup() != null) ? user.igroup().iname() : "");
                } else {
                    sb.getResource().put("userid", user.id());
                    sb.getResource().put("username", user.iname());
                    sb.getResource()
                      .put("gid",
                        (user.igroup() != null) ? user.igroup().id() : "-1");
                    sb.getResource()
                      .put("gname",
                        (user.igroup() != null) ? user.igroup().iname() : "");
                }

                util.manualSave("APP_INFO_RECEIPT", sb, conn);
                
                manager.updateInvolvementCount(ifid);

                conn.commit();

                request.setAttribute("result", "{success: true}");
            } else {
                request.setAttribute("result",
                    "{success:false, errorCode: '-2'}");
            }
        } catch (Exception ex) {
            request.setAttribute("result", "{success:false, errorCode: '-1'}");
            ISystem.catchException(request, this, ex);
            conn.rollback();
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("jsonresult");
    }

    /**
     * 新闻评论list
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward list(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        IUser user = ISystem.getSessionUser(request);

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        String ifid = StringTool.checkString(param.get("id"));

        String start = StringTool.checkString(param.get("start"), "0");

        String size = StringTool.checkString(param.get("limit"), "10");

        String pageNO = String.valueOf((Integer.parseInt(start) / Integer.parseInt(
                    size)) + 1);

        String sql1 = "SELECT COUNT(AF_ID) FROM APP_INFO_RECEIPT WHERE AF_ID = " +
            ifid + " AND RSTATUS = 1";
        String sql2 = "SELECT * FROM APP_INFO_RECEIPT WHERE AF_ID = " + ifid +
            " AND RSTATUS = 1 ORDER BY RTIME ASC";

        String url = "";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            QueryJack plus = QueryJackFactory.getInstance()
                                             .createQueryJack(false);

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, size);
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
            List resultList = plus.work();

            // 获得跳转控制
            Controller controller = plus.getController("form1");

            // 设置调转类型
            controller.setType("input");

            // 显示标签
            Label label = plus.getLabel();

            // 设置显示标签类型
            label.setType("href");

            JSONArray jsonArray = JSONArray.fromObject(resultList);

            String jsonString = "{success: true,pageNO: '" + pageNO +
                "',pageCount:'" + label.totalfan() + "',\"totalCount\":\"" +
                label.totaldata() + "\",\"infoList\":";
            jsonString += jsonArray.toString();
            jsonString += "}";

            request.setAttribute("result", jsonString);
        } catch (Exception ex) {
            request.setAttribute("result",
                "{success: false,pageNO : '0', pageCount : '0',\"totalCount\":\"-1\"}");
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("jsonresult");
    }
}
